﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Common.Entitys.CommonLogs;

namespace Common.Utils
{
    public class SerialPortService
    {
        //1表示接收到左侧数据，2表示右侧接收到数据
        private int _recLRFlag = 1;

        SerialPortHelp portClient = null;

        public event Action<double, double> SerialPortCurrentDisEvent;

        public double LeftDistance { get; set; }
        public double RightDistance { get; set; }

        public SerialPortService(string port)
        {
            portClient = new SerialPortHelp(port, BaudRates.BR_38400, System.IO.Ports.Parity.None, DataBits.Eight, System.IO.Ports.StopBits.One);
            OpenPort();
            InitPort();
            Task.Factory.StartNew(SensoPartQuerey);
        }

        public void OpenPort()
        {
            portClient.Open();
        }

        public void ClosePort()
        {
            portClient.Close();
        }

        private void InitPort()
        {
            int countL = 0;
            portClient.DataReceived += new Action<List<byte>>(datapool =>
            {
                if (datapool.Count >= 6)
                {
                    int count = datapool.Count;
                    if (datapool[0] == 0x81 && datapool[1] == 0x06 && datapool[2] == 0x59 ||
                        datapool[0] == 0x82 && datapool[1] == 0x06 && datapool[2] == 0x59 )
                    {
                        byte h = Convert.ToByte(datapool[3] & 0x3F);

                        byte l = Convert.ToByte(datapool[4] & 0x3F);
                        int d = BitConverter.ToInt32(BitConverter.GetBytes((h << 6) + l), 0);

                        if (datapool[0] == 0x81)
                        {
                            LeftDistance = Math.Round((double)((1 - ((double)d) / 4095) * 220 + 80), 2);
                            _recLRFlag = 2;
                        }
                        else if (datapool[0] == 0x82)
                        {
                            RightDistance = Math.Round((double)((1 - ((double)d) / 4095) * 220 + 80), 2);
                            _recLRFlag = 1;
                        }

                        datapool.RemoveRange(0, 6);
                        if (SerialPortCurrentDisEvent != null)
                        {
                            SerialPortCurrentDisEvent(LeftDistance, RightDistance);
                        }
                    }
                    else
                    {
                        countL = countL + 1;
                        datapool.RemoveRange(0, count);
                        ErrorLogEntity errorLogEntity = new ErrorLogEntity($"报错次数：{ countL}");
                        LogHelp.AddLog(errorLogEntity);
                    }
                }
            });

        }

        private void SensoPartQuerey()
        {
            int count = 0;
            while (true)
            {

                if (_recLRFlag == 1)
                {
                    byte[] data = new byte[] { 0x81, 0x04, 0x41, 0x44 };
                    portClient.Write(data);
                    _recLRFlag = -1;
                }
                else if (_recLRFlag == 2)
                {
                    byte[] data = new byte[] { 0x82, 0x04, 0x41, 0x47 };
                    portClient.Write(data);
                    _recLRFlag = -1;
                }

                if (count == 8)
                {
                    _recLRFlag = 1;
                    count = 0;
                }
                else
                {
                    count++;
                }

                Thread.Sleep(50);
            }

        }
    }
}
